<script setup lang="ts">
import type { DefaultRow } from '@/types/RoleAuthorization';
import { LsIcon } from '@lingshu/icon';
import { computed, h, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { formatTimestampToLocalDateString } from '@/utils/TimeFormatUtil';
import { useRoleAuthorization } from '../hooks/UseRoleAuthorization.ts';
import ViewTheTree from './components/ViewTheTree.vue';
import style from './role.module.scss';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  roleData: {
    type: Object as () => Partial<DefaultRow>,
    default: () => ({}),
  },
  orgTreeCode: {
    type: String,
    default: '',
  },
});

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
}>();
const {
  // 状态
  activePermissionType,
  treeData,
  propsConfig,
  treeInheritanceData,
  treeAllData,
  loading,
  allRef,
  inheritanceRef,

  // 方法
  switchPermissionType,
  handleSave,
  getTreeRefHandler,
} = useRoleAuthorization();

const { t } = useI18n();

// 响应式数据
const dialogVisible = ref(false);
const activeTab = ref('basic');
const formData = ref<DefaultRow>({});

// 侧边栏菜单项
const sidebarItems = [
  { id: 'basic', name: 'authorization.sidebar.basic' },
  { id: 'function', name: 'authorization.sidebar.function' },
  { id: 'data', name: 'authorization.sidebar.data' },
  { id: 'log', name: 'authorization.sidebar.log' },
  { id: 'column', name: 'authorization.sidebar.column' },
];

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
  if (newVal) {
    formData.value = { ...props.roleData };
  }
}, {
  immediate: true,
});

// 监听 dialogVisible 变化并同步到父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});
const searchIcon = h(LsIcon, {
  'font-family': 'iconfont',
  'value': 'icon-Search',
  'class': 'lst-gray5 text-14px!',
} as any);
const searchPlaceholder = t('roleAuthorization.searchFunction');
// 关闭对话框
function handleClose() {
  activeTab.value = 'basic';
  if (allRef.value) {
    allRef.value.clearText();
  }
  if (inheritanceRef.value) {
    inheritanceRef.value.clearText();
  }
  dialogVisible.value = false;
}

// 切换标签页
function handleTabChange(tabId: string) {
  activeTab.value = tabId;
  if (tabId === 'function') {
    switchPermissionType('all', { roleId: props.roleData?.roleId, orgCode: props.orgTreeCode });
  }
}

const subVisible = computed(() => formData.value.subVisible !== 0);
</script>

<template>
  <ElDialog
    v-model="dialogVisible"
    :title="t('roleAuthorization.assignPermissions')"
    :before-close="handleClose"
    class="role-info-dialog"
  >
    <!-- Dialog 内容区域 -->
    <div :class="style['dialog-body']">
      <!-- 左侧导航 -->
      <div class="dialog-sidebar">
        <div
          v-for="item in sidebarItems"
          :key="item.id"
          class="sidebar-item"
          :class="{ active: activeTab === item.id }"
          @click="handleTabChange(item.id)"
        >
          <span>{{ t(item.name) }}</span>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="dialog-content">
        <!-- 基本信息 -->
        <div v-show="activeTab === 'basic'" class="content-section" :class="{ active: activeTab === 'basic' }">
          <h3 class="section-title">
            {{ t('roleAuthorization.roleInfo') }}
          </h3>
          <ElForm :model="formData" label-width="110px">
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem :label="t('roleAuthorization.roleCode')" label-position="top">
                  <span class="form-value-item">{{ formData.roleCode }}</span>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem :label="t('roleAuthorization.roleName')" label-position="top">
                  <span class="form-value-item">{{ formData.roleName }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="24">
                <ElFormItem :label="t('roleAuthorization.permissionDescription')" label-position="top">
                  <span class="form-value-item">{{ formData.description }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem :label="t('roleAuthorization.inheritedFrom')" label-position="top">
                  <span class="form-value-item">{{ (formData.inheritedOrgName && formData.inheritedRoleName)
                    ? `${String(formData.inheritedOrgName)}/${String(formData.inheritedRoleName)}`
                    : (String(formData.inheritedOrgName ?? '') || String(formData.inheritedRoleName ?? '') || '') }}</span>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem :label="t('roleAuthorization.subordinateVisible')" label-position="top">
                  <el-switch v-model="subVisible" disabled />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="24">
                <ElFormItem :label="t('roleAuthorization.status')" label-position="top">
                  <el-radio v-model="formData.status" disabled :label="1">
                    {{ t('roleAuthorization.normal') }}
                  </el-radio>
                  <el-radio v-model="formData.status" disabled :label="0">
                    {{ t('roleAuthorization.disabled') }}
                  </el-radio>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="24">
                <ElFormItem :label="t('roleAuthorization.remark')" label-position="top">
                  <span class="form-value-item">{{ formData.remark }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem :label="t('roleAuthorization.creator')" label-position="top">
                  <span class="form-value-item">{{ formData.createName }}</span>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem :label="t('roleAuthorization.createTime')" label-position="top">
                  <span class="form-value-item">{{ formData.createTime ? formatTimestampToLocalDateString(formData.createTime) : formData.createTime }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="24">
              <ElCol :span="12">
                <ElFormItem :label="t('roleAuthorization.updater')" label-position="top">
                  <span class="form-value-item">{{ formData.updateName }}</span>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem :label="t('roleAuthorization.updateTime')" label-position="top">
                  <span class="form-value-item">{{ formData.updateTime ? formatTimestampToLocalDateString(formData.updateTime) : formData.updateTime }}</span>
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </div>

        <!-- 功能权限 -->
        <div v-show="activeTab === 'function' " class="content-section" :class="{ active: activeTab === 'function' }">
          <h3 class="section-title">
            {{ t('roleAuthorization.functionalPermission') }}
          </h3>
          <div class="permission-tabs-container">
            <div class="permission-type-selector">
              <div
                class="permission-type-item" :class="{ active: activePermissionType === 'all' }"
                @click="switchPermissionType('all', { roleId: props.roleData?.roleId, orgCode: orgTreeCode })"
              >
                <span class="permission-label">{{ t('roleAuthorization.allPermissions') }}</span>
              </div>
              <div
                class="permission-type-item" :class="{ active: activePermissionType === 'inherited' }"
                @click="switchPermissionType('inherited', { roleId: props.roleData?.roleId, orgCode: orgTreeCode })"
              >
                <span class="permission-label">{{ t('roleAuthorization.inheritedPermissions') }}</span>
              </div>

              <div
                class="permission-type-item" :class="{ active: activePermissionType === 'assigned' }"
                @click="switchPermissionType('assigned', { roleId: props.roleData?.roleId, orgCode: orgTreeCode })"
              >
                <span class="permission-label">{{ t('roleAuthorization.assignedPermissions') }}</span>
              </div>
            </div>
            <div v-show="activePermissionType === 'all'" v-loading="loading" class="permission-Inheritance-content">
              <ViewTheTree ref="allRef" :data="treeAllData" />
            </div>
            <div v-show="activePermissionType === 'inherited'" v-loading="loading" class="permission-Inheritance-content">
              <ViewTheTree ref="inheritanceRef" :data="treeInheritanceData" />
            </div>

            <div v-show="activePermissionType === 'assigned'" v-loading="loading" class="permission-content">
              <MiTreeSelector
                :ref="getTreeRefHandler(activeTab)" :data="treeData"
                node-key="id" :props="propsConfig" :show-bottom="false" mode="all"
                :custom-text="{
                  leftSearchPlaceholder: searchPlaceholder,
                  rightSearchPlaceholder: searchPlaceholder,
                }"
                :search-icon="searchIcon "
                :original-tree-structure="true"
              />
            </div>
            <ElButton
              v-if="activePermissionType === 'assigned'" type="primary" class="transfer-save"
              @click="handleSave"
            >
              {{ t('roleAuthorization.save') }}
            </ElButton>
          </div>
        </div>

        <!-- 数据权限 -->
        <div v-show="activeTab === 'data' " class="content-section" :class="{ active: activeTab === 'data' }">
          <h3 class="section-title">
            {{ t('roleAuthorization.dataPermission') }}
          </h3>
          <div class="text-placeholder">
            <hy-empty />
          </div>
        </div>

        <!-- 行级权限 -->
        <div v-show="activeTab === 'log' " class="content-section" :class="{ active: activeTab === 'log' }">
          <h3 class="section-title">
            {{ t('roleAuthorization.rowLevelPermission') }}
          </h3>
          <div class="text-placeholder">
            <hy-empty />
          </div>
        </div>
        <!-- 列级权限 -->
        <div v-show="activeTab === 'column' " class="content-section" :class="{ active: activeTab === 'log' }">
          <h3 class="section-title">
            {{ t('roleAuthorization.hierarchicalPermission') }}
          </h3>
          <div class="text-placeholder">
            <hy-empty />
          </div>
        </div>
      </div>
    </div>
  </ElDialog>
</template>
